package org.iot.iotserver.netty.command;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import org.iot.iotserver.netty.config.NettyConstant;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.Arrays;
import java.util.Optional;

/**
 * 单片机主动注册自己的名称
 */
public class RegisterCommandExecutor implements IYCommandExecutor<String> {

    private static final Log log = LogFactory.get();

    private final IIOTCommonService iotCommonService;

    public RegisterCommandExecutor(IIOTCommonService iotCommonService) {
        this.iotCommonService = iotCommonService;
    }

    @Override
    public boolean isMatching(String commandMetaData) {
        if(StrUtil.isEmpty(commandMetaData)) {
            return false;
        }
        String[] arr = commandMetaData.split("\\s+");
        if(arr.length < 2 || !"register".equalsIgnoreCase(arr[0])) {
            return false;
        }
        return true;
    }

    /**
     * 设备端设备数据上送的监控信息保存至缓存
     * @param args 第一个参数代表设备名称
     */
    @Override
    public String execute(ChannelHandlerContext context, String... args) {
        log.info("RegisterCommandExecutor({})", Arrays.toString(args));

        String deviceName = args[0];
        if(!NettyConstant.LEGAL_DEVICE_NAMES.contains(deviceName)) {
            throw new RuntimeException("非法名称");
        }

        Optional<Channel> channelOpt = iotCommonService.findFirstChannel(channel -> {
            if(channel.hasAttr(NettyConstant.DEVICE_KEY)) {
                return deviceName.equalsIgnoreCase(String.valueOf(channel.attr(NettyConstant.DEVICE_KEY).get()));
            }
            return false;
        });

        Channel currentChannel = context.channel();
        ChannelId currentChannelId = currentChannel.id();

        // 如果该名称已经设置
        if(channelOpt.isPresent()) {
            String existChannelId = channelOpt.get().id().asLongText();

            // 同一条管道, 则忽略
            if(currentChannelId.asLongText().equals(existChannelId)) {
                return "IGNORE\r\n";
            }

            // 不同管道, 关闭原管道
            channelOpt.get().close();
            return "REMOVE OTHER CHANNEL\r\n";
        }

        // 设置管道名称
        iotCommonService.setAttr(currentChannelId, "DEVICE_NAME", deviceName);

        log.info("当前客户端数量: {}", iotCommonService.getChannelSize());

        return "OK\r\n";
    }
}
